import tkinter as tk
import random
from tkinter import PhotoImage
import pygame
import os
import sys

def read_config(config_key, value_type=str, default=""):
    try:
        with open('config.txt', 'r', encoding='utf-8') as file:
            content = file.read()
            for line in content.split('\n'):
                line = line.strip()
                if line.startswith(config_key):
                    value = line.split('=')[1].strip()
                    if value_type == int:
                        return int(value)
                    else:
                        return value
    except:
        pass  
    return default

# 初始化 pygame 混音器
def init_music():
    try:
        pygame.mixer.init()
        # 检查音乐文件是否存在
        if os.path.exists("music.mp3"):
            pygame.mixer.music.load("music.mp3")
            pygame.mixer.music.play(-1)  # -1 表示循环播放
    except Exception as e:
        print(f"音乐播放失败: {e}")

# 存储所有弹窗的列表
windows_list = []
# 读取配置
WIND_WORDS = read_config("windows_words=", default="祝福文字")
MAX_WINDOWS = read_config("max_windows=", value_type=int, default=50)
print(MAX_WINDOWS)

def create_warm_tip():
    # 创建一个新窗口
    window = tk.Toplevel(root)
    try:
        icon = PhotoImage(file="heart.png")
        window.iconphoto(True, icon)
    except:
        pass
    
    # 设置窗口位置和大小
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    window_width = 250
    window_height = 60
    x = random.randrange(0, screen_width - window_width)
    y = random.randrange(0, screen_height - window_height)
    window.geometry(f"{window_width}x{window_height}+{x}+{y}")
    window.title(WIND_WORDS)

    # 随机选择祝福语和背景色
    with open('Sentence.txt', 'r', encoding='utf-8') as file:
        content = file.read()
        content = content.split('\n')
        bg_colors = ['lightpink', 'skyblue', 'lightgreen', 'lavender', 'lightyellow']
        contents = random.choice(content)
        bg = random.choice(bg_colors)

    # 创建标签显示文字
    tk.Label(window, text=contents, bg=bg, font=('华文彩云', 16), width=30, height=3).pack()
    window.attributes('-topmost', True)  # 窗口置顶
    
    # 将弹窗添加到列表
    windows_list.append(window)

def create_exit_popup():
    """创建退出程序的弹窗"""
    exit_window = tk.Toplevel(root)
    exit_window.title("程序结束")
    
    # 设置窗口在屏幕中央
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    window_width = 300
    window_height = 150
    x = (screen_width - window_width) // 2
    y = (screen_height - window_height) // 2
    exit_window.geometry(f"{window_width}x{window_height}+{x}+{y}")
    
    try:
        icon = PhotoImage(file="heart.png")
        exit_window.iconphoto(True, icon)
    except:
        pass
    
    # 设置窗口样式
    exit_window.configure(bg='lightpink')
    exit_window.attributes('-topmost', True)
    
    # 添加内容
    tk.Label(exit_window, 
             text="❤❤!!OVER!!❤❤", 
             bg='lightpink', 
             font=('华文彩云', 14),
             justify='center').pack(expand=True, pady=10)
    
    # 添加关闭按钮
    exit_button = tk.Button(exit_window, 
                       text="退出", 
                       command=exit_program,
                       font=('华文彩云', 12),
                       bg=exit_window['bg'],  # 使用窗口背景色
                       fg='black',            # 文字颜色
                       width=15,
                       height=2,
                       relief='flat',         # 扁平样式，无边框
                       bd=0,                  # 边框宽度为0
                       highlightthickness=0)  # 去掉高亮边框
    exit_button.pack(pady=10)
    
    # 也可以设置点击窗口任意位置关闭
    exit_window.bind('<Button-1>', lambda e: exit_program())

def exit_program():
    """退出程序"""
    try:
        pygame.mixer.music.stop()
        pygame.mixer.quit()
    except:
        pass
    root.quit()
    root.destroy()
    sys.exit()

def auto_pop_tips(interval=200):
    if len(windows_list) < MAX_WINDOWS:
        create_warm_tip()
        root.after(interval, auto_pop_tips, interval)
    else:
        # 达到最大数量后，延迟1秒开始关闭
        root.after(1000, close_windows_one_by_one)

def close_windows_one_by_one(interval=100):
    if windows_list:
        window = windows_list.pop()
        window.destroy()
        if windows_list:
            root.after(interval, close_windows_one_by_one, interval)
        else:
            # 所有弹窗关闭后，显示退出弹窗
            root.after(500, create_exit_popup)

# 创建主窗口（隐藏）
root = tk.Tk()
root.withdraw()

# 初始化并播放背景音乐
init_music()

# 启动定时弹窗
auto_pop_tips(200)
# 启动主循环
root.mainloop()